// * 用户 api 方法（login、logout、getInfo）
import { login, logout, getInfo } from '@/api/user'

// * 授权 api 方法(getToken、setToken、removeToken)
import { getToken, setToken, removeToken } from '@/utils/auth'

/**
 * * token 令牌
 * * info 用户信息
 * * name 用户名
 * * avatar 头像
 * * roles 角色权限
 * * permissions 权限标识数组
 */
const state = {
  token: getToken(),
  userInfo: {},
  id: '',
  userName: '',
  avatar: '',
  roles: [],
  permissions: [],
  expired: false // token 过期标示
}

const mutations = {
  // * 设置令牌
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // * 设置用户信息
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  // * 设置用户id
  SET_ID: (state, id) => {
    state.id = id
  },
  // * 设置用户名
  SET_USERNAME: (state, userName) => {
    state.userName = userName
  },
  // * 设置头像
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // * 设置角色
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  // * 设置权限
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  // * 设置过期标识
  SET_EXPIRED: (state, expired) => {
    state.expired = expired
  }
}

const actions = {
  setExpired({ commit }, expired) {
    return new Promise(resolve => {
      commit("SET_EXPIRED", expired)
      resolve()
    })
  },

  // * 登录
  login({ commit }, loginForm) {
    return new Promise((resolve, reject) => {
      login(loginForm).then(response => {
        const { data } = response

        commit('SET_TOKEN', data)
        setToken(data)

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // * 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('验证失败，请重新登录！')
        }

        const { permissions = [], roles = [], user = {} } = data

        if (!roles || roles.length <= 0) {
          reject('getInfo: roles 必须是一个非空数组！')
        }

        const avatar = user.avatar ? process.env.VUE_APP_BASE_API + user.avatar : require("@/assets/images/user-avatar.png")

        commit('SET_ROLES', roles)
        commit('SET_PERMISSIONS', permissions)

        commit('SET_USERINFO', user)
        commit('SET_USERNAME', user.userName)
        commit('SET_AVATAR', avatar)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出系统
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()

        // * 重置标签视图和缓存视图
        // dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 前端 登出
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      removeToken()
      resolve()
    })
  }
}

export default { state, mutations, actions }
